/*
 * Copyright (c) 2013 Joakim Lindskog
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.limewoodmedia.nsdroid.activities;

import static com.limewoodMedia.nsapi.holders.NationData.Shards.*;

import java.io.IOException;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.limewoodMedia.nsapi.exceptions.RateLimitReachedException;
import com.limewoodMedia.nsapi.exceptions.UnknownNationException;
import com.limewoodmedia.nsdroid.R;
import com.limewoodmedia.nsdroid.API;
import com.limewoodmedia.nsdroid.LoadingHelper;
import com.limewoodmedia.nsdroid.NationInfo;
import com.limewoodmedia.nsdroid.holders.NationDataParcelable;
import com.limewoodmedia.nsdroid.views.LoadingView;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Nation extends SherlockFragmentActivity {
	public static final String TAG = Nation.class.getName();

	private ViewGroup layout;
	private ImageView flag;
	private TextView fullName;
	private TextView motto;
	private TextView region;
	private TextView waStatus;
	private TextView influence;
	private TextView category;
	private TextView civilRights;
	private TextView economy;
	private TextView politicalFreedoms;
	private TextView description;
	
	private String nation;
	private NationDataParcelable data;
	private String errorMessage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
        setContentView(R.layout.nation);

        // Fetch flag
        LoadingHelper.loadHomeFlag(this);
        
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeButtonEnabled(true);
        
        Log.d(TAG, "DATA "+getIntent().getDataString());
        if(getIntent().getData() == null) {
        	nation = NationInfo.getInstance(this).getName().replace(' ', '_');
        }
        else {
        	nation = getIntent().getDataString().replace("com.limewoodMedia.nsdroid.nation://", "");
        }
        
        layout = (ViewGroup) findViewById(R.id.nation_layout);
        flag = (ImageView) findViewById(R.id.nation_flag);
        fullName = (TextView) findViewById(R.id.nation_name);
        motto = (TextView) findViewById(R.id.nation_motto);
        region = (TextView) findViewById(R.id.nation_region);
        region.setMovementMethod(LinkMovementMethod.getInstance());
        waStatus = (TextView) findViewById(R.id.nation_wa_status);
        influence = (TextView) findViewById(R.id.nation_influence);
        category = (TextView) findViewById(R.id.nation_category);
        civilRights = (TextView) findViewById(R.id.nation_civil_rights);
        economy = (TextView) findViewById(R.id.nation_economy);
        politicalFreedoms = (TextView) findViewById(R.id.nation_political_freedoms);
        description = (TextView) findViewById(R.id.nation_description);

        if(savedInstanceState == null) {
        	loadNation();
        } else {
        	// Restore
        	data = savedInstanceState.getParcelable("nation_data");
        	doSetup();
        }
    }
    
    private void loadNation() {
    	layout.setVisibility(View.GONE);
    	final LoadingView loadingView = (LoadingView) findViewById(R.id.loading);
    	LoadingHelper.startLoading(loadingView, R.string.loading_nation, this);
    	errorMessage = getResources().getString(R.string.general_error);
        new AsyncTask<Void, Void, Boolean>() {
        	protected Boolean doInBackground(Void...params) {
				try {
	                data = API.getInstance(Nation.this).getNationInfo(nation,
	                		FREEDOMS, CATEGORY, FULL_NAME, MOTTO, FLAG,
	                		POPULATION, ADMIRABLE, CUSTOM_LEADER, NOTABLE,
	                		SENSIBILITIES, GOVERNMENT_DESCRIPTION, TAX_RATE,
	                		INDUSTRY_DESCRIPTION, LEGISLATION, CRIME, NAME,
	                		ANIMAL, ANIMAL_TRAIT, CUSTOM_RELIGION, CURRENCY,
	                		REGION, WA_STATUS, INFLUENCE, CUSTOM_CAPITAL);
	                
	                // Load flag
	                data.flagBitmap = LoadingHelper.loadFlag(data.flagURL, Nation.this);
	                
	                return true;
				} catch (RateLimitReachedException e) {
					e.printStackTrace();
					errorMessage = getResources().getString(R.string.rate_limit_reached);
				} catch (UnknownNationException e) {
					e.printStackTrace();
					errorMessage = getResources().getString(R.string.unknown_nation);
				} catch (RuntimeException e) {
					e.printStackTrace();
					errorMessage = e.getMessage();
				} catch (IOException e) {
					e.printStackTrace();
					errorMessage = e.getMessage();
				}
				
				return false;
        	};
        	
        	protected void onPostExecute(Boolean result) {
        		LoadingHelper.stopLoading(loadingView);
        		
        		if(result) {
                	layout.setVisibility(View.VISIBLE);
        			doSetup();
        		}
        		else {
        			Toast.makeText(Nation.this, errorMessage, Toast.LENGTH_SHORT).show();
        		}
        	};
        }.execute();
    }
    
    private void doSetup() {
    	int ori = getResources().getConfiguration().orientation;
		setTitle(data.name);
		flag.setImageBitmap(data.flagBitmap);
		fullName.setText(data.fullName);
		motto.setText(Html.fromHtml("\""+data.motto+"\""));
		region.setText(Html.fromHtml("<b>"+getString(R.string.region)+":</b> "+
				"<a href=\"com.limewoodMedia.nsdroid.region://"+data.region
				.replace(' ', '_')+"\">"+data.region+"</a>"));
		switch(data.worldAssemblyStatus) {
		case NON_MEMBER:
			waStatus.setVisibility(View.GONE);
			break;
		case WA_MEMBER:
			waStatus.setText(getResources().getString(R.string.wa_member));
			if(waStatus.getVisibility() != View.VISIBLE) {
				waStatus.setVisibility(View.VISIBLE);
			}
			break;
		case WA_DELEGATE:
			waStatus.setText(getResources().getString(R.string.wa_delegate));
			if(waStatus.getVisibility() != View.VISIBLE) {
				waStatus.setVisibility(View.VISIBLE);
			}
			break;
		}
		influence.setText(getResources().getString(R.string.influence)+": "+data.influence);
        category.setText(getString(R.string.category)+": "+data.category);
        civilRights.setText(getString(R.string.civil_rights)+":" + (ori == Configuration.ORIENTATION_LANDSCAPE
        		? "\n" : " ") + data.freedoms.civilRights);
        economy.setText(getString(R.string.economy)+":" + (ori == Configuration.ORIENTATION_LANDSCAPE
        		? "\n" : " ") + data.freedoms.economy);
        politicalFreedoms.setText(getString(R.string.political_freedoms)+":" + (ori == Configuration.ORIENTATION_LANDSCAPE
        		? "\n" : " ") + data.freedoms.politicalFreedoms);
        description.setText(data.getDescription());
        layout.setVisibility(View.VISIBLE);
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	
    	outState.putParcelable("nation_data", data);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.menu_nation, menu);
        return true;
    }

    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
	        case android.R.id.home: {
	        	Intent i = new Intent(this, NSDroid.class);
	        	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        	startActivity(i);
	        	break;
	        }
            case R.id.menu_nation: {
            	// If this is your nation
            	if(nation.replace(' ', '_').equalsIgnoreCase(
            			NationInfo.getInstance(this).getName().replace(' ', '_'))) {
            		loadNation();
            	}
            	Intent i = new Intent(this, Nation.class);
            	startActivity(i);
            	break;
            }
	        case R.id.menu_region: {
	        	Intent i = new Intent(this, Region.class);
	        	startActivity(i);
	        	break;
	        }
	        case R.id.menu_issues: {
	        	Intent i = new Intent(this, Issues.class);
	        	startActivity(i);
	        	break;
	        }
	        case R.id.menu_add_nation_to_dossier:
	        	new AsyncTask<Void, Void, Void>() {
	        		@Override
	        		protected Void doInBackground(Void... params) {
	    	        	if(API.getInstance(Nation.this).checkLogin(Nation.this)) {
	    	        		try {
	    						if(API.getInstance(Nation.this).addNationToDossier(nation.replace(' ', '_').toLowerCase())) {
	    							runOnUiThread(new Runnable() {
	    								public void run() {
	    	    							Toast.makeText(Nation.this, R.string.nation_added_to_dossier, Toast.LENGTH_SHORT).show();
	    								};
	    							});
	    						}
	    					} catch (IOException e) {
	    						e.printStackTrace();
	    					}
	    	        	}
	        			return null;
	        		}
	        	}.execute();
	        	break;
            case R.id.menu_dossier: {
            	Intent i = new Intent(this, Dossier.class);
            	startActivity(i);
            	break;
            }
            case R.id.menu_refresh:
            	loadNation();
            	break;
            case R.id.menu_settings: {
            	Intent i = new Intent(this, Preferences.class);
            	startActivity(i);
            	break;
            }
        }
        return super.onOptionsItemSelected(item);
    }
}
